package yunjiao.javatutorials.designpatterns.observer;

import lombok.Getter;

import java.util.ArrayList;
import java.util.List;

/**
 * 新闻主题
 *
 * @author yangyunjiao
 */
public class NewsPublisher implements Subject {
    private final List<Observer> subscribers = new ArrayList<>();

    @Getter
    private String latestNews;
    @Getter
    private final String publisherName;

    public NewsPublisher(String name) {
        this.publisherName = name;
    }

    public void publishNews(String news) {
        this.latestNews = news;
        System.out.println("【" + publisherName + "】发布新闻: " + news);
        notifyObservers();
    }

    @Override
    public void registerObserver(Observer observer) {
        subscribers.add(observer);
        System.out.println(observer.getName() + " 订阅了 " + publisherName);
    }

    @Override
    public void removeObserver(Observer observer) {
        subscribers.remove(observer);
        System.out.println(observer.getName() + " 取消订阅 " + publisherName);
    }

    @Override
    public void notifyObservers() {
        for (Observer subscriber : subscribers) {
            subscriber.update(this);
        }
    }
}
